﻿using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

using BLL;
using Model;
using Utility;

namespace EvaluationSystem
{
    public partial class ActivityList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ((SiteSystemMaster)Master).InitMenu();
            ((SiteSystemMaster)Master).li1.Attributes.Add("class", "hover ccc");
            ((SiteSystemMaster)Master).b_hmenu1.Style.Clear();
            ((SiteSystemMaster)Master).b_hmenu2.Style.Add("display", "none");
            ((SiteSystemMaster)Master).b_hmenu3.Style.Add("display", "none");
            ((SiteSystemMaster)Master).s_menu1_1.Style.Add("COLOR", "#147ab8");
            ((SiteSystemMaster)Master).s_menu1_1.Style.Add("TEXT-DECORATION", "none"); 

            /*判断是否是管理员身份*/
            if (Session["username"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "<script>alert('请先登录系统!');top.location.href='../System/Login.aspx';</script>");
                return;
            }
            else
            {
                if (!IsPostBack)
                {
                    string users_id = Request.QueryString["users_id"];
                    if (!string.IsNullOrEmpty(users_id))
                    {
                        EnterpriseUserBLL userBLL = new EnterpriseUserBLL();
                        EnterpriseUser usr = userBLL.GetModel(Int32.Parse(users_id));
                        if (usr != null)
                        {
                            lblEnterpriseName.Text = usr.Username;
                            lblEnterpriseFull.Text = usr.Users_incname;
                        }
                    }

                    txtbActivityenterpriseuid.Text = users_id;
                    bind();
                    btnDelete.Attributes.Add("onclick", "return confirm('确实要删除这个项目吗?');");
                }
            }
        }

        private void bind()
        {
            if (string.IsNullOrEmpty(Request.QueryString["users_id"]))
            { 
                return; 
            }

            ActivityBLL temp = new ActivityBLL();
            
            DataSet ds = temp.GetActivityAll(Request.QueryString["users_id"]);

            if (ds == null) return;

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string aStatus = row["ACTIVITY_STATUS"].ToString();
                if (aStatus.Equals("开启项目"))
                {
                    row["ACTIVITY_STATUS"] = "已停止";
                }
                else if (aStatus.Equals("停止项目"))
                {
                    row["ACTIVITY_STATUS"] = "测试中";
                }
                else
                {
                }
            }

            grVActivityManage.DataSource = ds.Tables[0].DefaultView;
            grVActivityManage.DataSourceID = null;
            grVActivityManage.DataBind();
            temp = null;
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
           
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/System/AddActivity.aspx?users_id=" + txtbActivityenterpriseuid.Text + "&users_name=" + this.lblEnterpriseName.Text + "&users_incname=" + this.lblEnterpriseFull.Text);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ActivityBLL temp = new ActivityBLL();
            int selectCount = 0;
            int activity_id = 0;
            foreach (GridViewRow gr in grVActivityManage.Rows)
            {
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                if (chk.Checked)
                {
                    activity_id = int.Parse(grVActivityManage.DataKeys[gr.RowIndex].Values["activity_id"].ToString());
  
                    temp.Delete(activity_id);
                    selectCount++;
                }
            }
            if (0 == selectCount)
            {
                MessageBox.ResponseScript(this, "对不起，你没有选择记录!");
            }
            temp = null;
            Response.Redirect(Request.Url.ToString());
        }

        protected void CB_SelectAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < grVActivityManage.Rows.Count; i++)
            {
                GridViewRow gr = grVActivityManage.Rows[i];
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                chk.Checked = CB_SelectAll.Checked; //跟随全选按扭的状态变化;
            }
        }

        //导出测试结果、和企业端的功能一致。>>>>>>>>>>>>>>>>>>>>>>>>
        protected DataTable GetDimScore(string guid)
        {
            if (string.IsNullOrEmpty(guid))
            {
                return null;
            }
            else
            {
                RptBLL rptBLL = new RptBLL();
                DataTable dimTable = rptBLL.GetDimensionScore(guid);

                if (dimTable != null && dimTable.Rows.Count > 0)
                {
                    //删除智力维度在维度得分表里。
                    for (int k = 0; k < dimTable.Rows.Count; k++)
                    {
                        if (dimTable.Rows[k][5].ToString().Trim().Equals("3"))//智力潜能类
                        {
                            dimTable.Rows[k].Delete();
                            dimTable.AcceptChanges();
                            k--;
                        }
                    }

                    /*
                    //删除三个特殊维度在维度得分表里。
                    for (int s = 0; s < dimTable.Rows.Count; s++)
                    {
                        if (dimTable.Rows[s][1].ToString().Trim().Equals("社会称许性") ||
                            dimTable.Rows[s][1].ToString().Trim().Equals("心理健康度") ||
                            dimTable.Rows[s][1].ToString().Trim().Equals("诚信"))
                        {
                            dimTable.Rows[s].Delete();
                            dimTable.AcceptChanges();
                            s--;
                        }
                    }

                    //转换维度分数
                    for (int i = 0; i < dimTable.Rows.Count; i++)
                    {
                        int dimID = Int32.Parse(dimTable.Rows[i][0].ToString());//维度ID
                        int dimscore = Int32.Parse(dimTable.Rows[i][2].ToString());//维度原始分

                        if (dimTable.Rows[i][5].ToString().Trim().Equals("3"))//智力潜能类
                        {
                            dimTable.Rows[i][2] = rptBLL.ConvertZhiLiDimScore(dimID, dimscore);
                        }
                        else
                        {
                            dimTable.Rows[i][2] = rptBLL.ConvertDimScore(dimID, dimscore);
                        }
                    }*/
                    return dimTable;
                }
                else
                {
                    return null;
                }
            }
        }

        protected void grVActivityManage_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            TesterInfoBLL tinfoBLL = new TesterInfoBLL();
            int rowIndex = Int32.Parse(e.CommandArgument.ToString());//获取点击了第几行
            string usrID = Request.QueryString["users_id"];
            string aID = grVActivityManage.DataKeys[rowIndex].Values["activity_id"].ToString();
            string activityNM = grVActivityManage.DataKeys[rowIndex].Values["activity_name"].ToString();

            DataSet ds = tinfoBLL.GetListByEnterprise(usrID, aID);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                ds.Tables[0].Columns.Add("项目名称");
                for (int k = 0; k < ds.Tables[0].Rows.Count; k++)
                {
                    ds.Tables[0].Rows[k]["项目名称"] = activityNM;
                    string guid = ds.Tables[0].Rows[k]["tester_sn"].ToString();
                    DataTable dt = GetDimScore(guid);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            if (ds.Tables[0].Columns.IndexOf(dt.Rows[j]["DIMNM"].ToString()) != -1)
                            {
                                ds.Tables[0].Rows[k][dt.Rows[j]["DIMNM"].ToString()] = dt.Rows[j]["DIMSCORE"].ToString();
                            }
                            else
                            {
                                ds.Tables[0].Columns.Add(dt.Rows[j]["DIMNM"].ToString());
                                ds.Tables[0].Rows[k][dt.Rows[j]["DIMNM"].ToString()] = dt.Rows[j]["DIMSCORE"].ToString();
                            }
                        }
                    }
                }

                ds.Tables[0].Columns["tester_sn"].ColumnName = "测试序列号";
                ds.Tables[0].Columns["tester_email"].ColumnName = "E-Mail";
                ds.Tables[0].Columns["tester_name"].ColumnName = "姓名";
                ds.Tables[0].Columns["tester_sex"].ColumnName = "性别";
                ds.Tables[0].Columns["tester_birthdate"].ColumnName = "出生日期";
                ds.Tables[0].Columns["tester_education"].ColumnName = "学历";
                ds.Tables[0].Columns["tester_enterprise"].ColumnName = "公司名称";
                ds.Tables[0].Columns["tester_mobile"].ColumnName = "联系电话";
                ds.Tables[0].Columns["tester_experience"].ColumnName = "工作年龄";
                ds.Tables[0].Columns["tester_application"].ColumnName = "职务";
                ds.Tables[0].Columns["tester_matching"].ColumnName = "匹配度";
                ds.Tables[0].Columns["tester_consistencyscore"].ColumnName = "作答一致性";
                ds.Tables[0].Columns["tester_teststarttime"].ColumnName = "测试开始时间";
                ds.Tables[0].Columns["tester_testendtime"].ColumnName = "测试结束时间";
                ds.Tables[0].Columns["tester_experienceinner"].ColumnName = "本店工作经验";
                ds.Tables[0].Columns["tester_dealer"].ColumnName = "经销商名称";
                ds.Tables[0].Columns["tester_department"].ColumnName = "部门";

                ds.Tables[0].Columns.Remove("tester_enterpriseid");
                ds.Tables[0].Columns["项目名称"].SetOrdinal(0);//放置在第一列               


                //清空DBNull.Value值 2011.12.25
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        if (dr[dc] == DBNull.Value)
                        {
                            dr[dc] = string.Empty;
                        }
                    }
                }


                //开始导出
                string filePath = Server.MapPath("../userfiles") + @"\" +
                    activityNM + "_测评结果_" + DateTime.Now.ToString("yyyyMMdd_HH_mm_ss") + ".xls";
                string fileName = Path.GetFileName(filePath);
                ExcelLibrary.DataSetHelper.CreateWorkbook(filePath, ds);
                Stream stream = null;
                stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                long bytesToRead = stream.Length;
                Response.Clear();
                Response.ContentType = "application/ms-excel";
                Response.AddHeader("Content-Disposition", "attachment; filename=" +
                    HttpUtility.UrlEncode(fileName, Encoding.UTF8));

                while (bytesToRead > 0)
                {
                    if (Response.IsClientConnected)
                    {
                        byte[] buffer = new Byte[10000];
                        int length = stream.Read(buffer, 0, 10000);
                        Response.OutputStream.Write(buffer, 0, length);
                        Response.Flush();
                        bytesToRead = bytesToRead - length;
                    }
                    else
                    {
                        bytesToRead = -1;
                    }
                }
            }
        }
        //<<<<<<<<<<<<<<导出企业端考试结果，每人一行。

    }
}